﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Model;
using IDAL;
using System.Data.Entity;
namespace DAL
{
    public class SqlgameAccountDAL : IgameAccountDAL
    {
        GameGOEntities db = DbContextFactory.CreateDbContext();
        public IQueryable<gameAccount> GetGameAccounts(int uid)
        {
            return db.gameAccount.Where(a => a.userID == uid).OrderBy(a => a.userID);
        }
        public int AddGameAccount(int userid, int gameServer, string playName)
        {
            var gw = db.gameAccount.Where(a => a.gameServe == gameServer && a.playerName == playName).FirstOrDefault();
            if (gw != null);
            else
            {
                gw = new gameAccount()
                {
                    userID = userid,
                    gameServe = gameServer,
                    playerName = playName
                };
                db.gameAccount.Add(gw);
                db.SaveChanges();
                gw = db.gameAccount.Where(a => a.gameServe == gameServer && a.playerName == playName).FirstOrDefault();
            }
            return gw.ID;
        }
        public void UpdateGameAC(int id, int b, string c)
        {
            var user = db.gameAccount.Where(a => a.ID == id).FirstOrDefault();
            if (user == null) {
                var d = new gameAccount()
                {
                    userID = id,
                    gameServe = b,
                    playerName = c
                };
                db.gameAccount.Add(d);
            }
            else {
                user.gameServe = b;
                user.playerName = c;
                db.Set<gameAccount>().Attach(user);
                db.Entry(user).State = EntityState.Modified;
            }           
            db.SaveChanges();
        }
        public void RemoveGameAccount(int id)
        {
            var a = db.gameAccount.Where(o => o.ID == id).FirstOrDefault();
            db.gameAccount.Remove(a);
            db.SaveChanges();
        }
    }
}
